package com.doraro.coal.moudle.annoc.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.doraro.coal.exception.R;
import com.doraro.coal.moudle.annoc.model.entity.Annoc;
import com.doraro.coal.moudle.annoc.service.IAnnocService;
import com.doraro.coal.utils.ShiroUtils;
import com.doraro.coal.vo.PageParam;
import com.doraro.coal.vo.PageResult;
import com.doraro.coal.vo.UserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author doraro
 * @since 2019-10-11
 */
@RestController
@RequestMapping("/annoc")
public class AnnocRestController {
    @Autowired
    private IAnnocService annocService;


    @PostMapping("/list")
    public R<PageResult<Annoc>> page(@RequestBody PageParam<Annoc> annocPageParam) {
        final Long orgId = ShiroUtils.getUserEntity().getOrganize().getId();
        final Object status = annocPageParam.get("status");
        final Page<Annoc> annocPage = annocPageParam.toPage();
        annocPage.setDesc("create_time");
        final IPage<Annoc> page = annocService.page(annocPage,
                Wrappers.<Annoc>lambdaQuery()
                        .eq(Annoc::getOrgId, orgId)
                .eq(status !=null,Annoc::getAnnocStatus,status)
        );
        return R.success(new PageResult<>(page.getTotal(), page.getRecords()));
    }

    @PostMapping("/pub")
    public R<PageResult<Annoc>> pagePub(@RequestBody PageParam<Annoc> annocPageParam){
        final Long orgId = ShiroUtils.getUserEntity().getOrganize().getId();
        final Page<Annoc> annocPage = annocPageParam.toPage();
        annocPage.setDesc("publish_time");
        final IPage<Annoc> page = annocService.page(annocPage,
                Wrappers.<Annoc>lambdaQuery()
                        .eq(Annoc::getOrgId, orgId)
                        .eq(Annoc::getAnnocStatus,1)
        );
        return R.success(new PageResult<>(page.getTotal(), page.getRecords()));
    }
    @PostMapping("removeById")
    public R remove(@RequestParam Long id){
        annocService.removeById(id);
        return R.success();
    }

    @PostMapping("/saveOrUpdate")
    public R<Annoc> saveOrUpdate(@RequestBody Annoc annoc) {
        if (annoc.getAnnocStatus().equals(1)) {
            annoc.setPublishTime(LocalDateTime.now());
        }
        final UserDto userEntity = ShiroUtils.getUserEntity();
        annoc.setOrgId(userEntity.getOrgId());
        annoc.setAuthor(userEntity.getNickName());
        annocService.saveOrUpdate(annoc);
        return R.success(annoc);
    }
}

